package com.test.thread.example01;
import java.time.LocalDateTime;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class BlockingThreadPoolExample2 {
    public static void main(String[] args) {
        int corePoolSize = 5;
        int maxPoolSize = 10;
        int queueCapacity = 10;

        // 创建一个线程池，使用ArrayBlockingQueue作为等待队列
        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, 0,
                                                             TimeUnit.SECONDS, new ArrayBlockingQueue<>(queueCapacity),
                                                             new ThreadPoolExecutor.CallerRunsPolicy());

        // 提交任务，当队列已满时会阻塞
        for (int i = 1; i <= 50; i++) {
            final int taskNumber = i;
            System.out.println(LocalDateTime.now() + " before submit " + i);
            executor.execute(() -> {
                System.out.println(LocalDateTime.now() + " Task " + taskNumber + " is running." + Thread.currentThread());
                try {
                    Thread.sleep(30000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });

            System.out.println(LocalDateTime.now() + " after submit " + i);
        }

        // 关闭线程池
        executor.shutdown();
    }
}
